package com.yl.auth.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.auth.model.entity.Bumen;
import com.yl.auth.service.BumenService;
import com.yl.auth.utils.tree.JSON2Tree;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 * 部门
 * @author
 * @since 2023-06-15
 */
@Api(tags = "人事行政-部门管理")
@RestController
@RequestMapping("/admin/auth/bumen")
public class BumenController {

    @Autowired
    private BumenService bumenService;

    @ApiOperation("修改信息")
    @PutMapping("/update")
    public Result update(@RequestBody Bumen bumen){
        bumen.setUpdateTime(LocalDateTime.now());
        boolean b = bumenService.updateById(bumen);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    @ApiOperation("修改前的回显")
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable Integer id){
        Bumen byId = bumenService.getById(id);
        return Result.ok(byId);
    }

    @ApiOperation("添加部门")
    @PostMapping("/save")
    public Result save(@RequestBody Bumen bumen){
        bumen.setCreateTime(LocalDateTime.now());
        boolean b = bumenService.save(bumen);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }

    @ApiOperation("删除信息")
    @GetMapping("/del/{id}")
    public Result del(@PathVariable Long id){
        boolean b = bumenService.removeById(id);
        if (b){
            return Result.ok();
        }else {
            return Result.fail();
        }
    }
    @ApiOperation("查询全部信息")
    @GetMapping("/bumenList")
    public Result bumenList(){
        List<Bumen> bumenList = bumenService.list();
        return Result.ok(bumenList);
    }
    @ApiOperation("获取部门信息")
    @GetMapping("/findDept")
    public Result findDept(){
        IPage<Bumen> iPage = bumenService.page(new Page<>(1,1000));
        // 就是将SysMenu列表通过parent_id关联，编程tree结构
        iPage.getRecords().forEach(obj->obj.buildCas());
        JSONArray result = JSON2Tree.listToTree(JSONArray.parseArray(com.alibaba.fastjson.JSON.toJSONString(iPage.getRecords())),"id","pid","children");
        return Result.ok(result);
    }
    @ApiOperation("通过父节点id添加子节点")
    @PostMapping("/addChilren/{id}")
    public Result addChilren(@RequestBody Bumen bumen,@PathVariable Integer id){
        bumenService.addChilren(bumen,id);
        return Result.ok();
    }

}
